package com.inkyi.assistant.app.notepad.event;

import com.inkyi.assistant.app.component.rsyntax.RSyntaxTextConfig;
import com.inkyi.assistant.app.component.rsyntax.RSyntaxTextEditor;
import com.inkyi.assistant.app.component.rsyntax.event.RSyntaxTextEvent;
import com.inkyi.assistant.app.component.rsyntax.event.RSyntaxTextListener;
import com.inkyi.assistant.app.notepad.NodeDataType;
import com.inkyi.assistant.app.notepad.NoteContext;
import com.inkyi.framework.common.event.InkActionEvent;
import com.inkyi.framework.common.utils.BeanUtils;
import com.inkyi.framework.docdb.DocProperties;
import com.inkyi.framework.docdb.DocRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 编辑器保存监听
 *
 * @author lihongkun
 * @date 2025/08/01
 */
public class EditorSaveListener implements RSyntaxTextListener {
    private static final Logger logger = LoggerFactory.getLogger(EditorSaveListener.class);

    @Override
    public void actionPerformed(InkActionEvent e) {
        if (Objects.equals(RSyntaxTextEvent.TYPE_DO_SAVE, e.getType())) {
            RSyntaxTextEditor source = (RSyntaxTextEditor) e.getSource();
            String content = source.getContent();
            String id = source.getId();
            RSyntaxTextConfig editConfig = source.getEditConfig();

            DocRecord record = NoteContext.DATA_SOURCE.findById(id);
            // 内容
            List<DocRecord> childrens = new ArrayList<>();
            DocRecord newChildren = new DocRecord();
            newChildren.setData(content);
            newChildren.setType(NodeDataType.NODE_TEXT.getKey());
            childrens.add(newChildren);
            record.setChildren(childrens);
            // 参数
            try {
                DocProperties properties = record.getProperties();
                properties.putAll(BeanUtils.beanToMap(editConfig));
                record.setProperties(properties);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
            NoteContext.DATA_SOURCE.update(record);
        }
    }

    private List<DocRecord> getChildren(DocRecord record) {
        List<DocRecord> childrens = record.getChildren();
        if (childrens == null || childrens.isEmpty()) {
            childrens = new ArrayList<>();
        }
        return childrens;

    }
}
